package com.hjj.filter;

import com.hjj.beans.User;
import com.hjj.services.UserServices;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.*;
import java.io.IOException;

//@WebFilter(urlPatterns = {"/static/settings/*", "/static/workbench/*"})
public class MyLoginFilter extends HttpFilter {
    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {

        String requestURI = req.getRequestURI();

        System.out.println("正在过滤【" + requestURI + "】页面");

        // 在没用spring的情况下使用HttpServletRequest对象获取HttpSession对象
        HttpSession session = req.getSession();

        // 获取登录用户数据
        User user = (User)session.getAttribute("user");

        // 判断是否登录
        if (user == null){
            System.out.println("过滤器正在试图使用cookie自动登录");

            // 看看有没有cookie[获取cookie中的数据]
            Cookie[] cookies = req.getCookies();

            // cookies如果为空直接登录失败
            if (cookies == null) {
                res.sendRedirect("/static/login.html");
                return;
            }

            String loginAct = "";
            String loginPwd = "";

            for (Cookie cookie : cookies) {
                if ("loginAct".equals(cookie.getName())){
                    loginAct = cookie.getValue();
                }else if ("loginPwd".equals(cookie.getName())){
                    loginPwd = cookie.getValue();
                }
            }

            // 使用业务查询用户是否存在
            // 获取业务对象
            ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
            UserServices userServicesFilter = context.getBean("userServicesFilterImp", UserServices.class);

            User userTemp = userServicesFilter.login(loginAct, loginPwd);

            if (userTemp == null){
                // 回到登录页面
                res.sendRedirect("/static/login.html");
            }else {
                // 自动登录成功，则把用户数据放到Session里面
                session.setAttribute("user", userTemp);
                // 放行
                chain.doFilter(req, res);
            }
        }else {
            // 放行
            chain.doFilter(req, res);
        }
    }
}
